package cn.ike.web.utils;


import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

/**
 * Jedis连接池的工具类
 */
@Component
public class JedisUtils {
    /**
     * 只创建一个连接池
     */
    private static JedisPool pool;

    //在静态代码块中创建连接池
    static {
        //用来读取属性文件的类，参数是：配置文件的文件名，没有扩展名
        ResourceBundle bundle = ResourceBundle.getBundle("jedis");
        String host = bundle.getString("host");
        int port = Integer.valueOf(bundle.getString("port"));
        int maxTotal = Integer.valueOf(bundle.getString("maxTotal"));
        int maxWaitMillis = Integer.valueOf(bundle.getString("maxWaitMillis"));

        //1.创建配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //设置参数：最大连接数
        poolConfig.setMaxTotal(maxTotal);
        //设置最长等待时间
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        //2.创建连接池对象
        pool = new JedisPool(poolConfig, host, port);
    }

    /**
     * 从连接池中获取连接对象
     */
    public static Jedis getJedis() {
        return pool.getResource();
    }
}